package by.yativem.ins.web.templates;

import java.io.IOException;

import org.apache.struts2.views.freemarker.FreemarkerResult;
import org.apache.struts2.views.freemarker.ScopesHashModel;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.config.entities.ActionConfig;

import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;

public class DecorateFreemarkerResult extends FreemarkerResult {

	private static final long serialVersionUID = 1L;

	private static final String DECORATOR = "/ftl/decorates/decorate.ftl";

	private String decorationLocation;

	private boolean isDecorate(ActionConfig actionConfig) {
		// boolean result;
		if ("false".equals(actionConfig.getParams().get("decorate"))) {
			return false;
		} else {
			return true;
		} 

	}

	public DecorateFreemarkerResult() { 
		super();  
	}

	public DecorateFreemarkerResult(String location) {
		super(location);
	}

	/**
	 * Execute this result, using the specified template locationArg.
	 * <p/>
	 * The template locationArg has already been interoplated for any variable
	 * substitutions
	 * <p/>
	 * this method obtains the freemarker configuration and the object wrapper
	 * from the provided hooks. It them implements the template processing
	 * workflow by calling the hooks for preTemplateProcess and
	 * postTemplateProcess
	 */
	@Override
	public void doExecute(String locationArg, ActionInvocation invocation) throws IOException, TemplateException {

		if (isDecorate(invocation.getProxy().getConfig())) {
			this.decorationLocation = locationArg;
			super.doExecute(DECORATOR, invocation);
		}else{
			super.doExecute(locationArg, invocation);
		}

		

	}

	/**
	 * Build the instance of the ScopesHashModel, including JspTagLib support
	 * <p/>
	 * Objects added to the model are
	 * <p/>
	 * <ul>
	 * <li>Application - servlet context attributes hash model
	 * <li>JspTaglibs - jsp tag lib factory model
	 * <li>Request - request attributes hash model
	 * <li>Session - session attributes hash model
	 * <li>request - the HttpServletRequst object for direct access
	 * <li>response - the HttpServletResponse object for direct access
	 * <li>stack - the OgnLValueStack instance for direct access
	 * <li>ognl - the instance of the OgnlTool
	 * <li>action - the action itself
	 * <li>exception - optional : the JSP or Servlet exception as per the
	 * servlet spec (for JSP Exception pages)
	 * <li>struts - instance of the StrutsUtil class
	 * </ul>
	 */

	@Override
	protected TemplateModel createModel() throws TemplateModelException {

		TemplateModel model = super.createModel();
		if (isDecorate(invocation.getProxy().getConfig())) {
			((ScopesHashModel) model).put("body", decorationLocation);
		}

		return model;

	}

}
